const { getUserCollections, getUserInfo } = require('../../utils/request');

Page({
  data: {
    bannerImageUrls: [
      'https://i0.hdslb.com/bfs/new_dyn/4172c3893c56aabc86773e46eb5d913d358972.jpg@progressive.webp',
      'https://i0.hdslb.com/bfs/new_dyn/7cf2b32b4e0b2d619b67a34a8da73ac9358972.jpg@progressive.webp',
      'https://i0.hdslb.com/bfs/article/0c7233206db43b00e19c781d3f3f59dc49143463.jpg@progressive.webp',
      'https://i0.hdslb.com/bfs/new_dyn/8be84355ce7f2ec16a8b64e53aeb2db525830969.png@progressive.webp',
      'https://i0.hdslb.com/bfs/new_dyn/d4313aef978886e7dbc1ec1c348eb47a358972.jpg@progressive.webp',
      'https://i0.hdslb.com/bfs/new_dyn/23b6435e006cc45cede4e9e109e3fb88358972.jpg@progressive.webp',
      'https://i0.hdslb.com/bfs/new_dyn/ffcf5285957aa52050ed43fb5caa686725830969.jpg@progressive.webp',
    ],
    bannerImageUrl: '',
    username: '',
    activeTab: 0,
    activeSubjectType: 0,
    collections: [],
    loading: true,
    refreshing: false,
    hasMore: true,
    currentPage: 1,
    pageSize: 5, // 每页5条数据
    showPageControls: true, // 控制分页按钮显示
    totalPages: 1, // 总页数
    
    collectionTypes: [
      { id: 0, name: '想看', type: 1 },
      { id: 1, name: '看过', type: 2 },
      { id: 2, name: '在看', type: 3 },
      { id: 3, name: '搁置', type: 4 },
      { id: 4, name: '抛弃', type: 5 }
    ],
    
    subjectTypes: [
      { id: 0, name: '全部类型' },
      { id: 1, name: '动画', type: 2 },
      { id: 2, name: '书籍', type: 1 },
      { id: 3, name: '游戏', type: 4 },
      { id: 4, name: '音乐', type: 3 },
      { id: 5, name: '三次元', type: 6 }
    ],
    
    dropdownOptions: [
      { text: '全部类型', value: 0 },
      { text: '动画', value: 1 },
      { text: '书籍', value: 2 },
      { text: '游戏', value: 3 },
      { text: '音乐', value: 4 },
      { text: '三次元', value: 5 }
    ]
  },

  getRandomImageUrl() {
    const urls = this.data.bannerImageUrls;
    const randomIndex = Math.floor(Math.random() * urls.length);
    return urls[randomIndex];
  },

  // 检查登录状态
  checkLoginAndLoadData() {
    const username = wx.getStorageSync('username');
    const accessToken = wx.getStorageSync('accessToken');
    
    if (!username || !accessToken) {
      // 未登录，跳转到登录页
      wx.redirectTo({
        url: '/pages/login/login?redirect=/pages/home/home'
      });
      return;
    }
    
    // 已登录，加载数据
    this.loadCollections();
  },

  async onLoad() {
    this.checkLoginAndLoadData();
    this.setData({
      bannerImageUrl: this.getRandomImageUrl()
    });
    try {
      // 获取用户ID
      const userId = wx.getStorageSync('username'); // 这里实际存储的是用户ID
      
      // 获取用户详细信息
      const userInfo = await getUserInfo(userId);
      
      this.setData({
        // 优先使用nickname，没有则使用username（用户ID）
        username: userInfo.nickname || `用户${userId}`
      });
      
      this.loadCollections();
    } catch (error) {
      console.error('获取用户信息失败:', error);
      this.setData({
        username: 'Bangumi用户'
      });
      this.loadCollections();
    }
  },

  onShow() {
    if (this.getTabBar) {
      this.getTabBar().init();
    }
  },

  async loadCollections() {
    const { 
      activeTab, 
      activeSubjectType, 
      currentPage, 
      pageSize,
      collectionTypes,
      subjectTypes 
    } = this.data;
    
    this.setData({ loading: true });
    
    try {
      const collectionType = collectionTypes[activeTab].type;
      const subjectType = activeSubjectType === 0 ? undefined : subjectTypes[activeSubjectType].type;
      const username = wx.getStorageSync('username');
      
      if (!username) {
        throw new Error('未获取到用户名，请先登录');
      }
      
      const params = {
        type: collectionType,
        limit: pageSize,
        offset: (currentPage - 1) * pageSize
      };
      
      if (subjectType) {
        params.subject_type = subjectType;
      }
      
      const res = await getUserCollections(
        username, 
        subjectType,  // 可能是null
        collectionType,  // 一定有值
        pageSize,
        (currentPage - 1) * pageSize
      );
  
    
    const formattedData = res.data.map(item => ({
      id: item.subject_id,
      title: item.subject.name_cn || item.subject.name,
      alias: item.subject.name,
      cover: item.subject.images?.medium || '/images/default-cover.jpg',
      infoItems: [
        `类型: ${this.getTypeName(item.subject.type)}`,
        `${this.formatTime(item.updated_at)}`
      ],
      isPrivate: item.private,
      // 修正这里：只有当comment存在且不为空时才显示，否则不显示roast属性
      roast: item.comment || undefined, // undefined时组件不会显示吐槽区域
      _rawData: item
    }));

    // 计算总页数
    const totalPages = Math.ceil(res.total / pageSize) || 1;

    this.setData({
      collections: formattedData,
      loading: false,
      total: res.total,
      totalPages: totalPages,
      hasMore: currentPage < totalPages
    });
  } catch (error) {
    console.error('加载收藏失败:', error);
    wx.showToast({
      title: error.message || '加载收藏失败',
      icon: 'none'
    });
    this.setData({
      loading: false,
      collections: []
    });
  }
},

  // 获取类型名称
  getTypeName(type) {
    const types = {
      1: '书籍',
      2: '动画',
      3: '音乐',
      4: '游戏',
      6: '三次元'
    };
    return types[type] || '未知';
  },

  // 映射收藏状态
  mapCollectionType(type) {
    const map = {
      1: 'wish',
      2: 'collect',
      3: 'doing',
      4: 'on_hold',
      5: 'dropped'
    };
    return map[type] || 'default';
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '未知时间';
    try {
      const date = new Date(timeStr);
      return `收藏于 ${date.getMonth() + 1}月${date.getDate()}日`;
    } catch (e) {
      return '未知时间';
    }
  },

  
  // 上一页方法
  prevPage() {
    if (this.data.currentPage <= 1 || this.data.loading) return;
    this.setData({
      currentPage: this.data.currentPage - 1
    });
    this.loadCollections();
  },

  // 下一页方法
  nextPage() {
    if (this.data.currentPage >= this.data.totalPages || this.data.loading) return;
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    this.loadCollections();
  },

  // 修改onRefresh方法
  onRefresh() {
    this.setData({
      currentPage: 1,
      collections: [],
      hasMore: true
    });
    this.loadCollections();
  },

  // 修改onTabChange和onSubjectTypeChange方法
  onTabChange(e) {
    const activeTab = e.detail.index;
    this.setData({
      activeTab,
      currentPage: 1,
      collections: [],
      hasMore: true
    });
    this.loadCollections();
  },

  onSubjectTypeChange(e) {
    const activeSubjectType = e.detail;
    this.setData({
      activeSubjectType,
      currentPage: 1,
      collections: [],
      hasMore: true
    });
    this.loadCollections();
  },

  onItemClick(e) {
    const itemData = e.detail.itemData;
    wx.navigateTo({
      url: `/pages/item-detail/item-detail?id=${itemData.id}`
    });
  }
});